package cn.lblbc.webbrowser

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.view.ContextMenu
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.webkit.CookieManager
import android.webkit.DownloadListener
import android.webkit.WebChromeClient
import android.webkit.WebStorage
import android.webkit.WebView
import android.webkit.WebView.HitTestResult
import android.webkit.WebViewClient
import android.widget.ProgressBar
import android.widget.Toast
import androidx.fragment.app.Fragment
import cn.lblbc.webbrowser.utils.CustomDownloader
import cn.lblbc.webbrowser.utils.DownloadUtils
import cn.lblbc.webbrowser.utils.IncognitoManager
import cn.lblbc.webbrowser.utils.PermissionManager
import cn.lblbc.webbrowser.utils.ImageCollector

class WebViewFragment : Fragment() {
    private lateinit var webView: WebView
    private lateinit var progressBar: ProgressBar
    private var url: String = "https://www.baidu.com"
    private var title: String = ""
    private lateinit var downloadUtils: DownloadUtils
    private lateinit var permissionManager: PermissionManager
    private lateinit var imageCollector: ImageCollector
    private var customDownloader: CustomDownloader? = null

    companion object {
        private const val ARG_URL = "url"

        fun newInstance(url: String): WebViewFragment {
            val fragment = WebViewFragment()
            val args = Bundle()
            args.putString(ARG_URL, url)
            fragment.arguments = args
            return fragment
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            url = it.getString(ARG_URL) ?: "https://www.baidu.com"
        }
        
        // 初始化工具类
        context?.let {
            downloadUtils = DownloadUtils(it)
            permissionManager = PermissionManager(it)
            imageCollector = ImageCollector(it)
            customDownloader = (activity as? MainActivity)?.customDownloader
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_web_view, container, false)
        webView = view.findViewById(R.id.webView)
        progressBar = view.findViewById(R.id.progressBar)
        setupWebView()
        return view
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun setupWebView() {
        // 检查是否处于无痕模式
        val incognitoManager = context?.let { IncognitoManager(it) }
        val isIncognito = incognitoManager?.isIncognitoMode() ?: false
        
        webView.settings.apply {
            javaScriptEnabled = true
            domStorageEnabled = !isIncognito // 无痕模式下禁用DOM存储
            loadWithOverviewMode = true
            useWideViewPort = true
            builtInZoomControls = true
            displayZoomControls = false
            
            // 无痕模式下禁用缓存
            if (isIncognito) {
                cacheMode = android.webkit.WebSettings.LOAD_NO_CACHE
                // setAppCacheEnabled is deprecated in newer Android versions
            } else {
                cacheMode = android.webkit.WebSettings.LOAD_DEFAULT
            }
            
            // 添加额外设置以提高下载兼容性
            javaScriptCanOpenWindowsAutomatically = true
            loadsImagesAutomatically = true
            blockNetworkImage = false
            blockNetworkLoads = false
            
            // 设置默认的MIME类型和编码
            defaultTextEncodingName = "UTF-8"
            
            // 设置用户代理
            val originalUserAgent = userAgentString
            userAgentString = "$originalUserAgent WebBrowser/1.0"
            
            // 允许混合内容
            mixedContentMode = android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
            
            // 允许文件访问
            allowFileAccess = true
            allowContentAccess = true
        }
        
        // 无痕模式下禁用Cookie
        if (isIncognito) {
            CookieManager.getInstance().setAcceptCookie(false)
            WebStorage.getInstance().deleteAllData()
        }

        webView.webViewClient = object : WebViewClient() {
            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                super.onPageStarted(view, url, favicon)
                progressBar.visibility = View.VISIBLE
                
                // 显示MainActivity中的进度条
                (activity as? MainActivity)?.showWebProgress()
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                progressBar.visibility = View.GONE
                title = webView.title ?: ""
                (activity as? MainActivity)?.updateTabTitle(this@WebViewFragment, title)
                
                // 隐藏MainActivity中的进度条
                (activity as? MainActivity)?.hideWebProgress()
                
                // 开始收集网页图片
                imageCollector.startCollecting(webView)
            }

            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                if (url == null) return false
                
                // 检查是否为特殊协议URL
                if (isSpecialSchemeUrl(url)) {
                    handleSpecialSchemeUrl(url)
                    return true
                }
                
                // 对于普通URL，让WebView继续加载
                return false
            }
        }

        webView.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                super.onProgressChanged(view, newProgress)
                progressBar.progress = newProgress
                
                // 更新MainActivity中的进度条
                (activity as? MainActivity)?.updateWebProgress(newProgress)
            }
        }
        
        // 设置下载监听器
        webView.setDownloadListener { downloadUrl, userAgent, contentDisposition, mimeType, contentLength ->
            try {
                // 检查URL是否有效
                if (downloadUrl.isNullOrEmpty()) {
                    Toast.makeText(context, "下载URL无效", Toast.LENGTH_SHORT).show()
                    return@setDownloadListener
                }
                
                // 检查Android版本
                val isAndroid13Plus = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU

                // 检查权限状态
                val hasPermissions = permissionManager.hasAllPermissions()

                // 检查下载目录是否可写
                val downloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                val canWrite = downloadDir.canWrite()
                // 检查应用专用下载目录
                val appDownloadDir = context?.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
                val appDirCanWrite = appDownloadDir?.canWrite() ?: false
                // Android 13+ 不需要存储权限，直接下载
                if (isAndroid13Plus || hasPermissions) {
                    // 显示下载开始提示
                    Toast.makeText(context, "准备下载...", Toast.LENGTH_SHORT).show()

                    if (isAndroid13Plus && customDownloader != null) {
                        // 在Android 13+上使用自定义下载器
                        customDownloader?.downloadFile(downloadUrl, userAgent, contentDisposition, mimeType)
                    } else {
                        // 在Android 12及以下使用系统DownloadManager
                        downloadUtils.downloadFile(downloadUrl, userAgent, contentDisposition, mimeType)
                    }
                } else {
                    // 保存下载信息，以便权限授予后继续下载
                    activity?.let { act ->
                        // 创建一个下载信息的Bundle
                        val downloadInfo = Bundle().apply {
                            putString("url", downloadUrl)
                            putString("userAgent", userAgent)
                            putString("contentDisposition", contentDisposition)
                            putString("mimeType", mimeType)
                        }
                        
                        // 将下载信息保存到Activity中
                        if (act is MainActivity) {
                            act.setPendingDownload(downloadInfo)
                            
                            // 主动申请权限
                            permissionManager.requestAllPermissions(act)
                        }
                    } ?: run {
                        Toast.makeText(context, "无法请求所需权限", Toast.LENGTH_SHORT).show()
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                Toast.makeText(context, "下载失败: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }

        // 设置长按菜单
        registerForContextMenu(webView)
        webView.setOnCreateContextMenuListener { menu, view, menuInfo ->
            // 获取长按的元素信息
            val result = (view as WebView).hitTestResult
            if (result.type == HitTestResult.IMAGE_TYPE || result.type == HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
                // 长按图片
                menu.add(0, 1, 0, "在新标签页中打开图片")
                menu.add(0, 2, 0, "复制图片地址")
                menu.add(0, 3, 0, "保存图片")
            } else if (result.type == HitTestResult.SRC_ANCHOR_TYPE) {
                // 长按链接
                menu.add(0, 4, 0, "在新标签页中打开链接")
                menu.add(0, 5, 0, "复制链接地址")
            }
        }

        webView.loadUrl(url)
    }

    // 处理上下文菜单的点击事件
    override fun onContextItemSelected(item: MenuItem): Boolean {
        val result = webView.hitTestResult
        val url = result.extra // This can be null

        when (item.itemId) {
            1 -> {
                // 在新标签页中打开图片
                if (url != null) {
                    (activity as? MainActivity)?.addNewTab(url)
                }
                return true
            }
            2 -> {
                // 复制图片地址
                if (url != null) {
                    copyToClipboard(url)
                    Toast.makeText(context, "图片地址已复制", Toast.LENGTH_SHORT).show()
                }
                return true
            }
            3 -> {
                // 保存图片
                if (url != null) {
                    saveImage(url)
                }
                return true
            }
            4 -> {
                // 在新标签页中打开链接
                if (url != null) {
                    (activity as? MainActivity)?.addNewTab(url)
                }
                return true
            }
            5 -> {
                // 复制链接地址
                if (url != null) {
                    copyToClipboard(url)
                    Toast.makeText(context, "链接地址已复制", Toast.LENGTH_SHORT).show()
                }
                return true
            }
            else -> return super.onContextItemSelected(item)
        }
    }

    // 复制文本到剪贴板
    private fun copyToClipboard(text: String?) {
        if (text.isNullOrEmpty()) return
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            val clipboardManager = context?.getSystemService(Context.CLIPBOARD_SERVICE) as? android.content.ClipboardManager
            clipboardManager?.let {
                val clipData = android.content.ClipData.newPlainText("URL", text)
                it.setPrimaryClip(clipData)
            }
        } else {
            // 兼容旧版本
            val clipboardManager = context?.getSystemService(Context.CLIPBOARD_SERVICE) as? android.text.ClipboardManager
            clipboardManager?.text = text
        }
    }

    // 保存图片
    private fun saveImage(imageUrl: String?) {
        if (imageUrl.isNullOrEmpty()) return
        
        try {
            // 检查权限
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
                // Android 13+ 不需要存储权限，直接下载
                downloadImage(imageUrl)
            } else if (permissionManager.hasAllPermissions()) {
                // 有存储权限，直接下载
                downloadImage(imageUrl)
            } else {
                // 没有权限，保存下载信息并请求权限
                activity?.let { act ->
                    val downloadInfo = Bundle().apply {
                        putString("url", imageUrl)
                        putString("contentDisposition", null)
                        putString("mimeType", "image/*")
                    }
                    
                    if (act is MainActivity) {
                        act.setPendingDownload(downloadInfo)
                        permissionManager.requestAllPermissions(act)
                    }
                }
            }
        } catch (e: Exception) {
            Toast.makeText(context, "保存图片失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }

    // 下载图片
    private fun downloadImage(imageUrl: String?) {
        if (imageUrl.isNullOrEmpty()) return
        
        // 由于上面已经检查过非空，可以安全地使用非空类型
        val nonNullImageUrl: String = imageUrl
        
        try {
            Toast.makeText(context, "准备下载图片...", Toast.LENGTH_SHORT).show()
            
            // 获取WebView的User-Agent
            val userAgent = webView.settings.userAgentString
            // 内容处置参数使用空字符串
            val contentDisposition = ""
            
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU && customDownloader != null) {
                // 在Android 13+上使用自定义下载器
                customDownloader?.downloadFile(nonNullImageUrl, userAgent, contentDisposition, "image/*")
            } else {
                // 在Android 12及以下使用系统DownloadManager
                downloadUtils.downloadFile(nonNullImageUrl, userAgent, contentDisposition, "image/*")
            }
        } catch (e: Exception) {
            Toast.makeText(context, "下载图片失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }

    fun canGoBack(): Boolean {
        return if (::webView.isInitialized) webView.canGoBack() else false
    }

    fun goBack() {
        if (::webView.isInitialized && webView.canGoBack()) {
            webView.goBack()
        }
    }

    fun canGoForward(): Boolean {
        return if (::webView.isInitialized) webView.canGoForward() else false
    }

    fun goForward() {
        if (::webView.isInitialized && webView.canGoForward()) {
            webView.goForward()
        }
    }

    fun loadUrl(url: String) {
        if (::webView.isInitialized) {
            // 检查是否为特殊协议URL
            if (isSpecialSchemeUrl(url)) {
                handleSpecialSchemeUrl(url)
            } else {
                webView.loadUrl(url)
            }
        }
    }

    /**
     * 检查是否为特殊协议URL
     */
    private fun isSpecialSchemeUrl(url: String): Boolean {
        val specialSchemes = listOf("baiduboxapp", "weixin", "alipay", "taobao", "tbopen", "market", "mttbrowser")
        return specialSchemes.any { url.startsWith("$it://") }
    }

    /**
     * 处理特殊协议URL
     */
    private fun handleSpecialSchemeUrl(url: String) {
        try {
            // 处理mttbrowser协议的特殊情况
            if (url.startsWith("mttbrowser://url=")) {
                // 提取实际的URL部分
                val actualUrl = url.substring("mttbrowser://url=".length)
                // 创建Intent并交给系统处理，而不是在当前WebView中加载
                val intent = Intent(Intent.ACTION_VIEW, Uri.parse(actualUrl))
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                context?.startActivity(intent)
            } else {
                val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                context?.startActivity(intent)
            }
        } catch (e: Exception) {
            // 如果无法启动相应应用，显示提示
            Toast.makeText(context, "无法打开此链接，请确保已安装相应应用", Toast.LENGTH_LONG).show()
        }
    }

    fun getCurrentUrl(): String {
        return if (::webView.isInitialized) webView.url ?: "" else ""
    }

    fun getTitle(): String {
        return title.ifEmpty { "新标签页" }
    }
    
    /**
     * 获取网页缩略图
     */
    fun getThumbnail(): Bitmap? {
        return if (::webView.isInitialized) {
            try {
                // 获取WebView的宽高
                val width = webView.width
                val height = webView.height
                
                // 检查宽高是否有效
                if (width <= 0 || height <= 0) {
                    return null
                }
                
                // 创建位图
                val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565)
                val canvas = Canvas(bitmap)
                
                // 绘制WebView内容到画布
                webView.draw(canvas)
                
                bitmap
            } catch (e: Exception) {
                e.printStackTrace()
                null
            }
        } else {
            null
        }
    }
}